/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package three2learn.Controller;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import three2learn.Model.Student;
import three2learn.service.HibernateUtil;
import three2learn.service.MD5;

/**
 *
 * @author Alberto
 */
public class LoginController extends HttpServlet {
    /* HTTP GET request */

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        String email = null;
        String password = null;
        if (request.getParameter("email") != null) {
            email = request.getParameter("email");
        }
        if (request.getParameter("password") != null) {
            password = MD5.encrypt(request.getParameter("password"));
        }
        doorsturen(request, response, checkLogin(email, password));
    }

    public boolean checkLogin(String username, String password) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Student tmp = (Student) session.load(Student.class, username);
        if (tmp.getPassw().equalsIgnoreCase(password)) {
            return true;
        }
        return false;
    }

    private void doorsturen(HttpServletRequest request, HttpServletResponse response, boolean correctPass)
            throws ServletException, IOException {

        request.setAttribute("correctpassword", correctPass);
        if (correctPass) {
            System.out.println("WORKS");
        }

        String address = "/index.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}